package org.example.system.controller.monitor;

import lombok.RequiredArgsConstructor;
import org.example.common.core.constants.GlobalConstants;
import org.example.common.core.domain.R;
import org.example.common.core.utils.page.Pager;
import org.example.common.excel.utils.ExcelUtil;
import org.example.common.log.annotation.OperatorLog;
import org.example.common.log.enums.BusinessType;
import org.example.common.redis.utils.RedisUtils;
import org.example.common.security.annotation.PreAuthorize;
import org.example.system.domain.vo.SysLoginLogVo;
import org.example.system.service.ISysLoginLogService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 系统访问记录
 *
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/logininfor")
public class SysLoginLogController  {

    private final ISysLoginLogService logininforService;

    /**
     * 获取系统访问记录列表
     */
    @PreAuthorize(hasAnyPermi = {"monitor:logininfor:list"})
    @PostMapping("/list")
    public Pager<SysLoginLogVo> list(@RequestBody Pager pageQuery) {
        return logininforService.selectPageLogininforList(pageQuery);
    }

    /**
     * 导出系统访问记录列表
     */
    @OperatorLog(title = "登录日志", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasAnyPermi = {"monitor:logininfor:export"})
    @PostMapping("/export")
    public void export(@RequestBody Pager pageQuery, HttpServletResponse response) {
        List<SysLoginLogVo> list = logininforService.selectLogininforList(pageQuery);
        ExcelUtil.exportExcel(list, "登录日志", SysLoginLogVo.class, response);
    }

    /**
     * 批量删除登录日志
     * @param infoIds 日志ids
     */
    @PreAuthorize(hasAnyPermi = {"monitor:logininfor:remove"})
    @OperatorLog(title = "登录日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{infoIds}")
    public R<Void> remove(@PathVariable Long[] infoIds) {
        return R.toAjax(logininforService.deleteLogininforByIds(infoIds));
    }

    /**
     * 清理系统访问记录
     */
    @PreAuthorize(hasAnyPermi={"monitor:logininfor:remove"})
    @OperatorLog(title = "登录日志", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public R<Void> clean() {
        logininforService.cleanLogininfor();
        return R.ok();
    }

    @PreAuthorize(hasAnyPermi = {"monitor:logininfor:unlock"})
    @OperatorLog(title = "账户解锁", businessType = BusinessType.OTHER)
    @GetMapping("/unlock/{userName}")
    public R<Void> unlock(@PathVariable("userName") String userName) {
        String loginName = GlobalConstants.PWD_ERR_CNT_KEY + userName;
        if (RedisUtils.hasKey(loginName)) {
            RedisUtils.deleteObject(loginName);
        }
        return R.ok();
    }

}
